package com.shoothzj.example.storage.mariadb.hibernate;

import com.shoothzj.example.storage.api.IDatabase;
import com.shoothzj.example.storage.api.module.TableInfo;
import com.shoothzj.example.storage.hibernate.HibernateService;
import com.shoothzj.example.storage.mariadb.MariadbSqlUtil;
import org.hibernate.SessionFactory;

import java.math.BigInteger;
import java.util.List;

public class MariadbHibernateDatabaseService extends HibernateService implements IDatabase {
    public MariadbHibernateDatabaseService(SessionFactory sessionFactory) {
        super(sessionFactory);
    }

    @Override
    public List<String> schemas() {
        return (List<String>) this.nativeQuery("SELECT schema_name FROM information_schema.SCHEMATA");
    }

    @Override
    public void createTable(String schema, String tableName, TableInfo tableInfo) {
        String ddl = MariadbSqlUtil.getDdl(tableName, tableInfo);
        this.nativeUpdate(ddl);
    }

    public long countTable(String schema, String tableName) {
        String sql = "SELECT COUNT(*) FROM ";
        BigInteger bigInteger = (BigInteger) this.nativeQuery(sql + schema + "." + tableName).get(0);
        return bigInteger.longValue();
    }
}
